﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.IO;
using System.Data.SqlClient;
using System.Web.Mvc;
using NxPartyAffairsOpen.Models;

namespace NxPartyAffairsOpen.Helpers
{
    public class CategoryHelper
    {
        public static List<SubCategoryModel> GetCategoryListByCategoryType(NXDBDataContext db, Guid appid, string type)
        {

            List<SubCategoryModel> list = db.Category.Where(l => l.Flag == "1" && l.CategoryType == type && l.AppID == appid).OrderBy(o => o.OrderNum)
                .Select(s => new SubCategoryModel { CategoryID = s.CategoryID, CategoryName = s.CategoryName, DisplayName = s.DisplayName, OrderNum = s.OrderNum }).ToList();

            return list;
        }
        public static List<SelectListItem> GetCategoryListByCategoryTypeToSelect(NXDBDataContext db, Guid appid, string type)
        {

            List<SelectListItem> list = db.Category.Where(l => l.Flag == "1" && l.CategoryType == type && l.AppID == appid).OrderBy(o => o.OrderNum)
                .Select(s => new SelectListItem { Text = s.DisplayName, Value = s.CategoryID.ToString(), Selected = false }).ToList();


            return list;
        }

        public static List<InformationModel> GetInfoList(Guid appid, Guid CategoryID, int pagesize, int pageindex, string order, ref int count, string where, bool isrecursive, bool usedistinct, int action)
        {

            //   DataTable dt = BLInformation.GetInformationList(appid, CategoryID.ToString(), "InfoCategory", "1", true, string.Empty, string.Empty, where, string.Empty, string.Empty, string.Empty, DateTime.MinValue, DateTime.MaxValue, DateTime.MinValue, DateTime.MaxValue, "AUDITED", string.Empty, order, pageindex, pagesize, ref count);



            DataTable dt = InformationHelper.GetPagingList("InfoGuid,Author,Title,SubTitle,GroupName,CreateTime,ShowTime", "vwInfoCategory", where, "ShowTime desc,CreateTime desc", pageindex, pagesize, usedistinct, action, ref count, CategoryID, isrecursive);

            List<InformationModel> list = new List<InformationModel>();

            foreach (DataRow item in dt.Rows)
            {
                InformationModel im = EntityHelper.ConvertToEntity(item, typeof(InformationModel)) as InformationModel;
                list.Add(im);
            }

            list = list.OrderByDescending(l => l.ShowTime).ThenByDescending(l => l.CreateTime).ToList();
            return list;
        }

        public static List<InformationModel> GetInfoListForFG(Guid appid, Guid CategoryID, int pagesize, int pageindex, ref int count, FGQueryModel query, bool isrecursive, bool usedistinct, int action)
        {
            string where = "1=1";
            if (query.Title.Trim() != string.Empty)
                where += " and Title like '%" + query.Title.Trim().Replace("'", "''") + "%'";
            if (query.WjClass.Trim() != string.Empty)
                where += " and BackNvarchar12 like '%" + query.WjClass.Trim().Replace("'", "''") + "%'";
            if (query.WjDept.Trim() != string.Empty)
                where += " and BackNvarchar1 like '%" + query.WjDept.Trim().Replace("'", "''") + "%'";
            if (query.WjType.Trim() != string.Empty)
                where += " and BackNvarchar2 like '%" + query.WjType.Trim().Replace("'", "''") + "%'";
            if (query.WjWh.Trim() != string.Empty)
                where += " and BackNvarchar like '%" + query.WjWh.Trim().Replace("'", "''") + "%'";
            DateTime dtime = DateTime.MinValue;
            if (query.Ssstart.Trim() != string.Empty)
            {
                if (DateTime.TryParse(query.Ssstart.Trim(), out dtime))
                {
                    where += " and BackNvarchar13 >= '" + dtime.ToString("yyyy-MM-dd") + "'";
                }
            }
            if (query.Ssend.Trim() != string.Empty)
            {
                if (DateTime.TryParse(query.Ssend.Trim(), out dtime))
                {
                    where += " and BackNvarchar13 <= '" + dtime.ToString("yyyy-MM-dd") + "'";
                }
            }
            if (query.Pubstart.Trim() != string.Empty)
            {
                if (DateTime.TryParse(query.Pubstart.Trim(), out dtime))
                {
                    where += " and ShowTime >= '" + dtime.ToString("yyyy-MM-dd") + "'";
                }
            }
            if (query.Pubend.Trim() != string.Empty)
            {
                if (DateTime.TryParse(query.Pubend.Trim(), out dtime))
                {
                    where += " and ShowTime <= '" + dtime.ToString("yyyy-MM-dd") + "'";
                }
            }

            //   DataTable dt = BLInformation.GetInformationList(appid, CategoryID.ToString(), "InfoCategory", "1", true, string.Empty, string.Empty, query.Title, string.Empty, string.Empty, string.Empty, DateTime.MinValue, DateTime.MaxValue, DateTime.MinValue, DateTime.MaxValue, "AUDITED", string.Empty, order, pageindex, pagesize, ref count);
            DataTable dt = InformationHelper.GetPagingList("InfoGuid,Author,Title,SubTitle,CreateTime,ShowTime,BackNvarchar1", "vwInfoCategoryEx", where, "ShowTime desc,CreateTime desc", pageindex, pagesize, usedistinct, action, ref count, CategoryID, isrecursive);


            List<InformationModel> list = new List<InformationModel>();

            foreach (DataRow item in dt.Rows)
            {
                InformationModel im = EntityHelper.ConvertToEntity(item, typeof(InformationModel)) as InformationModel;
                list.Add(im);
            }

            list = list.OrderByDescending(l => l.ShowTime).ThenByDescending(l => l.CreateTime).ToList();

            return list;
        }

        public static List<InformationModel> GetInfoListForSearch(Guid appid, Guid CategoryID, int pagesize, int pageindex, ref int count, FGQueryModel query, bool isrecursive, bool usedistinct, int action)
        {
            string where = "1=1";
            if (query.Title.Trim() != string.Empty)
                where += " and Title like '%" + query.Title.Trim().Replace("'", "''") + "%'";
            if (query.Author.Trim() != string.Empty)
                where += " and Author like '%" + query.Author.Trim().Replace("'", "''") + "%'";
            if (query.GroupName.Trim() != string.Empty)
                where += " and GroupName like '%" + query.GroupName.Trim().Replace("'", "''") + "%'";
            DateTime dtime = DateTime.MinValue;

            if (query.Pubstart.Trim() != string.Empty)
            {
                if (DateTime.TryParse(query.Pubstart.Trim(), out dtime))
                {
                    where += " and ShowTime >= '" + dtime.ToString("yyyy-MM-dd") + "'";
                }
            }
            if (query.Pubend.Trim() != string.Empty)
            {
                if (DateTime.TryParse(query.Pubend.Trim(), out dtime))
                {
                    where += " and ShowTime <= '" + dtime.ToString("yyyy-MM-dd") + "'";
                }
            }

            //   DataTable dt = BLInformation.GetInformationList(appid, CategoryID.ToString(), "InfoCategory", "1", true, string.Empty, string.Empty, query.Title, string.Empty, string.Empty, string.Empty, DateTime.MinValue, DateTime.MaxValue, DateTime.MinValue, DateTime.MaxValue, "AUDITED", string.Empty, order, pageindex, pagesize, ref count);
            DataTable dt = InformationHelper.GetPagingList("InfoGuid,Author,Title,SubTitle,CreateTime,ShowTime,GroupName", "vwInfoCategoryEx", where, "ShowTime desc,CreateTime desc", pageindex, pagesize, usedistinct, action, ref count, CategoryID, isrecursive);


            List<InformationModel> list = new List<InformationModel>();

            foreach (DataRow item in dt.Rows)
            {
                InformationModel im = EntityHelper.ConvertToEntity(item, typeof(InformationModel)) as InformationModel;
                list.Add(im);
            }

            list = list.OrderByDescending(l => l.ShowTime).ThenByDescending(l => l.CreateTime).ToList();

            return list;
        }

        public static List<CategoryModel> GetCategoryPathByCategoryID(Guid categoryid)
        {
            SqlParameter p = new SqlParameter("@CategoryID", SqlDbType.UniqueIdentifier);
            p.Value = categoryid;

            SqlConnection con = new SqlConnection(Config.IPSConnectionKey);
            con.Open();
            SqlCommand sqlcom = new SqlCommand("Proc_U_GetMenuPathByCategoryID", con);
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.Parameters.Add(p);

            SqlDataAdapter sda = new SqlDataAdapter(sqlcom);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            con.Close();

            List<CategoryModel> cmList = new List<CategoryModel>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                CategoryModel im = EntityHelper.ConvertToEntity(dr, typeof(CategoryModel)) as CategoryModel;
                cmList.Add(im);
            }

            List<CategoryModel> sorted = new List<CategoryModel>();
            List<CategoryModel> _tempList2 = cmList.Where(l => l.CategoryID == categoryid).ToList();
            Guid cid = Guid.Empty;
            if (_tempList2.Count > 0)
            {
                sorted.Add(_tempList2[0]);
                cid = new Guid(_tempList2[0].ParentID);
            }
            while (cid != Guid.Empty)
            {
                List<CategoryModel> _tempList = cmList.Where(l => l.CategoryID == cid).ToList();
                if (_tempList.Count > 0)
                {
                    sorted.Add(_tempList[0]);
                    cid = new Guid(_tempList[0].ParentID);
                }
                else
                    cid = Guid.Empty;
            }

            return sorted;
        }


        public static LeftMenuModel GetLeftMenu(Guid categoryid)
        {
            SqlParameter p = new SqlParameter("@CategoryID", SqlDbType.UniqueIdentifier);
            p.Value = categoryid;

            SqlConnection con = new SqlConnection(Config.IPSConnectionKey);
            con.Open();
            SqlCommand sqlcom = new SqlCommand("Proc_U_GetLeftMenu", con);
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.Parameters.Add(p);

            SqlDataAdapter sda = new SqlDataAdapter(sqlcom);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            con.Close();

            LeftMenuModel lmm = new LeftMenuModel();

            DataTable dtTop = ds.Tables[0];
            if (dtTop.Rows.Count > 0)
            {
                CategoryModel cm = EntityHelper.ConvertToEntity(dtTop.Rows[0], typeof(CategoryModel)) as CategoryModel;
                lmm.CategoryID = cm.CategoryID;
                lmm.CategoryName = cm.CategoryName;
                lmm.DisplayName = cm.DisplayName;
                lmm.OrderNum = cm.OrderNum;
                lmm.OuterUrl = cm.OuterUrl;
                lmm.ParentID = Guid.Empty.ToString();

                List<CategoryModel> sub = new List<CategoryModel>();

                DataTable subDt = ds.Tables[1];
                foreach (DataRow item in subDt.Rows)
                {
                    CategoryModel subcm = EntityHelper.ConvertToEntity(item, typeof(CategoryModel)) as CategoryModel;

                    List<SubCategoryModel> level3List = new List<SubCategoryModel>();

                    DataRow[] level3 = ds.Tables[2].Select("ParentID='" + subcm.CategoryID.ToString() + "'");
                    foreach (DataRow dr in level3)
                    {
                        SubCategoryModel scm = EntityHelper.ConvertToEntity(dr, typeof(SubCategoryModel)) as SubCategoryModel;
                        level3List.Add(scm);
                    }
                    subcm.SubCategory = level3List;
                    sub.Add(subcm);
                }
                lmm.Category = sub;
            }
            return lmm;
        }

        public static PicNewModel GetPicNews(Guid categoryid, string pre)
        {
            PicNewModel pnm = new PicNewModel();

            pnm.CategoryID = categoryid;

            string temp = string.Empty;
            int count = 0;
            DataTable dt = InformationHelper.GetPagingList("InfoGuid,Author,Title,SubTitle,CreateTime,ShowTime,MEDIAFILENAME", "vwInfoCategory", "MediaFileName is not null and MediaFileName <>''", "ShowTime desc ,CreateTime desc", 0, 10, false, 1, ref count, categoryid, false);
            string url = HttpContext.Current.Request.Url.Host;
            if (!url.EndsWith("/"))
                url += "/";
            url += HttpContext.Current.Request.ApplicationPath;
            if (!url.EndsWith("/"))
                url += "/";
            url = "http://" + url.Replace("//", "/");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string _tempUrl = Config.IPSServer + dt.Rows[i]["MEDIAFILENAME"].ToString();

                string _tempFileStore = dt.Rows[i]["MEDIAFILENAME"].ToString().ToLower().Replace("/" + Config.IPSAppName.ToLower(), "");
                string _target = HttpContext.Current.Server.MapPath("~/Images/Temp") + _tempFileStore;
                if (File.Exists(Config.IPSFileStore + _tempFileStore) && (!File.Exists(_target)))
                {
                    FileInfo fi = new FileInfo(Config.IPSFileStore + _tempFileStore);
                    if (!Directory.Exists(_target.ToLower().Replace(fi.Name.ToLower(), "")))
                    {
                        Directory.CreateDirectory(_target.ToLower().Replace(fi.Name.ToLower(), ""));
                    }
                    File.Copy(Config.IPSFileStore + _tempFileStore, _target, true);

                    _tempUrl = "../images/temp" + _tempFileStore;
                }
                if (File.Exists(_target))
                {

                    _tempUrl = "../images/temp" + _tempFileStore;
                }
                InformationModel im = EntityHelper.ConvertToEntity(dt.Rows[i], typeof(InformationModel)) as InformationModel;
                im.ShortTitle = im.Title;
                im.Title = "<img alt='' src='" + _tempUrl + "' />";
                im.ImgFile = _tempUrl;
                pnm.InformationList.Add(im);
            }

            pnm.InformationList = pnm.InformationList.OrderByDescending(l => l.ShowTime).ThenByDescending(l => l.CreateTime).ToList();

            return pnm;
        }
        public static PicNewModel2 GetPicNews(Guid categoryid, bool haslist, string pre)
        {
            PicNewModel2 pnm = new PicNewModel2();
            pnm.Pre = pre;
            pnm.CategoryID = categoryid;
            string script = string.Empty;
            string pics = "var pics" + pre + " = ";
            string links = " var links" + pre + " = ";
            string texts = " var texts" + pre + " = ";
            string temp = string.Empty;
            int count = 0;
            // DataTable dt = Wicresoft.IPS.ClientLib.ObjectModel.Information.GetInformationListByMediaFile(categoryid, "CommonInfo", false, true, true, 5, "ShowTime desc,CreateTime desc");
            DataTable dt = InformationHelper.GetPagingList("InfoGuid,Author,Title,SubTitle,CreateTime,ShowTime,MEDIAFILENAME", "vwInfoCategory", "MediaFileName is not null and MediaFileName <>''", "ShowTime desc ,CreateTime desc", 0, 5, false, 1, ref count, categoryid, false);
            string url = HttpContext.Current.Request.Url.Host;
            if (!url.EndsWith("/"))
                url += "/";
            url += HttpContext.Current.Request.ApplicationPath;
            if (!url.EndsWith("/"))
                url += "/";
            url = "http://" + url.Replace("//", "/");

            int k = dt.Rows.Count;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                k = i;
                if (k >= 1)
                    break;
                string _tempUrl = Config.IPSServer + dt.Rows[i]["MEDIAFILENAME"].ToString();

                string _tempFileStore = dt.Rows[i]["MEDIAFILENAME"].ToString().ToLower().Replace("/" + Config.IPSAppName.ToLower(), "");
                string _target = HttpContext.Current.Server.MapPath("~/Images/Temp") + _tempFileStore;
                if (File.Exists(Config.IPSFileStore + _tempFileStore) && (!File.Exists(_target)))
                {
                    FileInfo fi = new FileInfo(Config.IPSFileStore + _tempFileStore);
                    if (!Directory.Exists(_target.ToLower().Replace(fi.Name.ToLower(), "")))
                    {
                        Directory.CreateDirectory(_target.ToLower().Replace(fi.Name.ToLower(), ""));
                    }
                    File.Copy(Config.IPSFileStore + _tempFileStore, _target, true);

                    _tempUrl = "../images/temp" + _tempFileStore;
                }
                if (File.Exists(_target))
                {

                    _tempUrl = "../images/temp" + _tempFileStore;
                }
                script += "var imgUrl" + pre + i + " = encodeURI(\"" + _tempUrl + "\");\r\n";
                script += "var imgtext" + pre + i + " = \"" + Cut(dt.Rows[i]["TITLE"].ToString(), 20) + "\";\r\n";
                script += "var imgLink" + pre + i + " = encodeURI(\"" + url + "Portal/Details/" + dt.Rows[i]["INFOGUID"].ToString() + "\");\r\n";

                pics += temp + "imgUrl" + pre + i;
                links += temp + "imgLink" + pre + i;
                texts += temp + "imgtext" + pre + i;
                temp = "+\"|\"+";
            }

            if (dt.Rows.Count > 0)
                script += pics + ";\r\n" + links + ";\r\n" + texts + ";\r\n";
            else
            {
                script += pics + "'';\r\n" + links + "'';\r\n" + texts + "'';\r\n";

            }
            pnm.Scripts = script;

            if (haslist)
            {
                count = 0;
                //   DataTable dtInfo = BLInformation.GetInformationList(Config.AppID, categoryid.ToString(), "InfoCategory", "1", true, string.Empty, string.Empty,
                //    string.Empty, string.Empty, string.Empty, string.Empty, DateTime.MinValue, DateTime.MaxValue, DateTime.MinValue, DateTime.MaxValue, "AUDITED", string.Empty, "ShowTime desc,CreateTime desc", 0, 8, ref count);

                DataTable dtInfo = InformationHelper.GetPagingList("InfoGuid,Author,Title,SubTitle,CreateTime,ShowTime,ContentNoHtml", "vwInfoCategory", "", "ShowTime desc ,CreateTime desc", 0, 8, false, 1, ref count, categoryid, true);

                if (dtInfo.Rows.Count > 0)
                {
                    pnm.InfoGuid = new Guid(dtInfo.Rows[0]["InfoGuid"].ToString());
                    pnm.Title = dtInfo.Rows[0]["title"].ToString();
                    pnm.ShortTitle = pnm.Title;
                    if (pnm.Title.Length > 36)
                        pnm.ShortTitle = pnm.Title.Substring(0, 36) + "...";
                    pnm.ShortContent = "  " + dtInfo.Rows[0]["ContentNoHtml"].ToString();
                    if (pnm.ShortContent.Length > 230)
                        pnm.ShortContent = pnm.ShortContent.Substring(0, 230);
                    for (int j = 1; j < dtInfo.Rows.Count; j++)
                    {
                        InformationModel im = EntityHelper.ConvertToEntity(dtInfo.Rows[j], typeof(InformationModel)) as InformationModel;
                        pnm.InformationList.Add(im);

                    }
                    pnm.InformationList = pnm.InformationList.OrderByDescending(l => l.ShowTime).ThenByDescending(l => l.CreateTime).ToList();

                }
            }
            return pnm;
        }

        public static List<Category> GetCategoryList( List<Guid> IDs)
        {
            NXDBDataContext db = new NXDBDataContext();
            List<Category> list = db.Category.Where(l => l.Flag == "1" && IDs.Contains(l.CategoryID)).ToList();
            return list;
        }
        public static List<CategoryInfoModel> GetList(List<Guid> IDs)
        {
            List<CategoryInfoModel> lists = new List<CategoryInfoModel>();

            List<Category> categoryList = GetCategoryList(IDs);
            foreach (Guid item in IDs)
            {
                CategoryInfoModel AnalysisInfoList = new CategoryInfoModel();

                Category cate = categoryList.SingleOrDefault(l => l.CategoryID == item);
                if (cate != null)
                {

                    AnalysisInfoList.CategoryID = item;
                    AnalysisInfoList.DisplayName = cate.DisplayName;
                    int count = 0;
                    AnalysisInfoList.InformationList = CategoryHelper.GetInfoList(Config.AppID, item, 8, 0, "ShowTime", ref count, string.Empty, false, false, 1);
                    lists.Add(AnalysisInfoList);
                }
            }

            return lists;

        }

        public static string Cut(string str, int CharCount)
        {
            if (CharCount > 0)
            {
                if (str.ToString().Length > CharCount)
                    return str.ToString().Substring(0, CharCount) + "...";
            }
            return str.ToString();
        }


    }
}